<template>
  <div class="login-container">
    <h3>用户登录</h3>
    <el-form
      ref="login"
      :model="loginForm"
      :rules="loginRules"
      label-width="80px"
    >
      <span class="login_title">武汉智慧交通信息管理系统</span>

      <!-- 账号 -->
      <el-form-item label="用户名" prop="user_name">
        <el-input
          v-model="loginForm.user_name"
          placeholder="请输入用户名"
          prefix-icon="el-icon-user"
        ></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="user_password">
        <el-input
          v-model="loginForm.user_password"
          placeholder="请输入密码"
          prefix-icon="el-icon-key"
          show-password
        ></el-input>
      </el-form-item>

      <!-- 验证码 -->
      <el-form-item prop="input_IdentifyCode" label="验证码">
        <div id="identify_part">
          <el-input
            v-model.trim="loginForm.input_IdentifyCode"
            placeholder="请输入验证码"
            prefix-icon="el-icon-open"
          ></el-input>
          <div
            @click="refreshCode()"
            class="code"
            style="cursor: pointer"
            title="点击切换验证码"
          >
            <identify :identifyCode="identifyCode"></identify>
          </div>
        </div>
      </el-form-item>

      <!-- 登录按钮 -->
      <el-form-item id="login_now">
        <el-button type="primary" @click="submitForm" size="medium "
          >登&nbsp;&nbsp;录</el-button
        >
      </el-form-item>
      <!-- 注册按钮 -->
      <el-form-item class="register">
        <div>
          <router-link to="/register">没有账号？立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Identify from './components/Identify.vue'

export default {
  name: 'Login',
  components: { Identify },
  data() {
    var validateIdentifyCode = (rule, value, callback) => {
      if (!this.checkIdentifyCode()) {
        callback(new Error('验证码错误'))
        this.refreshCode()
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        user_name: '',
        user_password: '',
        input_IdentifyCode: '',
      },
      loginRules: {
        user_name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        user_password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        input_IdentifyCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { validator: validateIdentifyCode, trigger: ['blur'] },
        ],
      },
      users: [],
      identifyCode: '',
      identifyCodes: [
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
      ], //根据实际需求加入自己想要的字符
    }
  },
  created() {
    this.getAllUsers()
  },
  mounted() {
    this.refreshCode()
  },
  methods: {
    // 获取所用用户数据
    getAllUsers() {
      this.$http.get('/gg_user').then((res) => {
        this.users = res.result
        var userName = this.users
        console.log('aa', this.users)
      })
    },
    // 核对验证码
    checkIdentifyCode() {
      if (this.loginForm.input_IdentifyCode === this.identifyCode) {
        return true
      } else {
        return false
      }
    },
    // 生成随机数
    randomNum(min, max) {
      max = max + 1
      return Math.floor(Math.random() * (max - min) + min)
    },
    // 更新验证码
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
      console.log('当前验证码:', this.identifyCode)
    },
    // 随机生成验证码字符串
    makeCode(data, len) {
      console.log('data, len:', data, len)
      for (let i = 0; i < len; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length - 1)]
      }
    },
    // 登录验证
    submitForm() {
      // 通过$refs, 获取表单的组件对象
      this.$refs['login'].validate((valid) => {
        if (valid) {
          // 开始检验
          // 账号验证
          console.log(this.users)
          let user = this.users.find(
            (item) => item.user_name == this.loginForm.user_name
          )
          console.log(user)
          // 一、若用户存在，验证密码
          if (user) {
            // 1.账号和密码都正确，生成cookie
            if (user.user_password == this.loginForm.user_password) {
              var status = {
                user_id: user.user_id,
                user_name: user.user_name,
                user_type: user.user_type,
                user_password: user.user_password,
              }
              status = JSON.stringify(status)
              // 1-2. 发送ajax请求
              setTimeout(() => {
                // 1-3. 提示用户
                this.$message.success('登录成功')
                // 1-4设置coolie账户密码，设置cookie过期时间

                this.$cookies.set('status', status, 3600 * 24)
                console.log(status)
                // 1-5. 跳转
                this.$router.push('/home')
              }, 1000)
            } else {
              // 2.密码错误检验不通过
              this.$message({
                type: 'error',
                message: '用户名或者密码错误，请重新输入！',
                duration: 900,
              })
              // 提示用户
            }
          } else {
            // 二、若用户不存在，则报错
            this.$message({
              type: 'error',
              message: '用户名输入错误，请重新输入！',
              duration: 900,
            })
          }
        } else {
          // 检验不通过
          this.$message({
            type: 'error',
            message: '用户名或者密码不能为空',
          })
        }
      })
    },
  },
}
</script>

<style>
body {
  background: url('../assets/image/bg.png');
}
.login-container {
  width: 500px;
  margin: 50px auto;
  padding: 20px 20px;
  border: 1px solid #ccc;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0, 0, 5px rgba(0, 0, 0, 0.1);
}

.login-container h3 {
  text-align: center;
  margin-bottom: 20px;
}
.el-form .login_title {
  width: 100%;
  display: inline-block;
  margin: 0 auto 10px auto;
  color: #77c1d7;
  font-size: 24px;
  font-weight: 700;
  text-align: center;
}
#identify_part {
  display: flex;
  justify-content: space-between;
}
#identify_part .el-input {
  flex: 0.9;
}
#login_now {
  display: inline-block;
}
.register {
  display: inline-block;
  left: 100px;
}
</style>
